package com.example.list

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import com.example.list.databinding.ActivityMainBinding
import com.google.gson.Gson

class MainActivity : AppCompatActivity() {
    private lateinit var mBinding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        initAdapter()
    }

    private fun initAdapter() {
        val mList = getShopList()
        val mAdapter = ShopAdapter()
        val layoutManager = GridLayoutManager(this, 3)

        mBinding.rvShop.layoutManager = layoutManager
        mBinding.rvShop.adapter = mAdapter
        mAdapter.setList(mList)

        mAdapter.setGridSpanSizeLookup { _, _, position ->
            val model = mList[position]
            if (model.isHead == true){
                3
            } else{
                1
            }
        }
    }

    private fun getShopList(): ArrayList<ShopModel.Data.Children> {
        val shopModel = Gson().fromJson(strJson, ShopModel::class.java)
        val newList = ArrayList<ShopModel.Data.Children>()
        shopModel.data!![1].children?.forEach {
            val c = it
            c.isHead = true
            newList.add(c)
            it.children?.forEach { children ->
                val child = ShopModel.Data.Children()
                child.isHead = false
                child.id = children.id
                child.image = children.image
                child.label = children.label
                child.sort = children.sort
                child.superiorId = children.superiorId
                newList.add(child)
            }
        }
        return newList
    }
}